<template>
	<view class="goods-detail-page">
		<!-- 顶部导航 -->
		<view class="navbar">
			<view class="navbar-back" @click="goBack">
				<text class="icon-back">←</text>
			</view>
			<text class="navbar-title">{{ goodsInfo.goodsName || '加载中...' }}</text>
			<view class="navbar-right">
				<text class="navbar-icon" @click="handleShare">♻️</text>
				<!-- 收藏按钮 -->
				<text class="navbar-icon" :class="isCollected ? 'icon-collected' : ''" @click="toggleCollect">★</text>
			</view>
		</view>

		<!-- 商品图片 -->
		<view class="goods-img-container">
			<image :src="handleImgURL(goodsInfo.goodsImg)" mode="widthFix" class="goods-img" lazy-load
				placeholder="/static/images/default-goods.png"></image>
		</view>

		<!-- 商品基础信息 -->
		<view class="goods-base-info">
			<view class="goods-price-wrap">
				<text class="goods-price">¥{{ (goodsInfo.goodsPrice || 0).toFixed(2) }}</text>
				<text class="goods-original-price"
					v-if="goodsInfo.originalPrice">¥{{ (goodsInfo.originalPrice || 0).toFixed(2) }}</text>
				<text class="goods-sales" v-if="goodsInfo.salesNum">月售{{ goodsInfo.salesNum }}件</text>
			</view>
			<text class="goods-name">{{ goodsInfo.goodsName || '' }}</text>
		</view>

		<!-- 商品描述 -->
		<view class="goods-desc-container">
			<text class="desc-title">商品描述</text>
			<text class="goods-desc">{{ goodsInfo.goodsDesc || '暂无详细描述' }}</text>
		</view>

		<!-- 加载中提示 -->
		<view v-if="loading" class="loading-container">
			<view class="loading-spinner"></view>
		</view>

		<!-- 错误提示 -->
		<view v-if="errorMsg" class="error-container">
			<text class="error-icon">⚠️</text>
			<text class="error-text">{{ errorMsg }}</text>
			<button class="retry-btn" @click="getGoodsDetail">重新加载</button>
		</view>

		<!-- 底部操作栏 -->
		<view class="cart-operate-bar" v-if="!errorMsg && goodsInfo.isOnSale === 1">
			<!-- 美化后的数量控制按钮 -->
			<view class="count-control">
				<button class="count-btn minus-btn" @click="decreaseCount" :disabled="count <= 1">
					<text class="count-icon">-</text>
				</button>
				<text class="count-num">{{ count }}</text>
				<button class="count-btn plus-btn" @click="increaseCount">
					<text class="count-icon">+</text>
				</button>
			</view>
			<!-- 美化后的操作按钮 -->
			<button class="add-to-cart-btn" @click="addToCart">
				<text class="btn-text">加入购物车</text>
			</button>
			<button class="buy-now-btn" @click="buyNow">
				<text class="btn-text">立即购买</text>
			</button>
		</view>
		<view class="cart-operate-bar offline" v-if="!errorMsg && goodsInfo.isOnSale === 0">
			<text class="offline-text">该商品已下架</text>
		</view>
	</view>
</template>

<script>
	import {
		getDetailById
	} from '@/api/goods.js'
	import {
		addCart
	} from '@/api/cart.js'
	import {
		baseUrl
	} from '@/utils/config.js'

	export default {
		data() {
			return {
				goodsId: 0,
				goodsInfo: {},
				loading: false,
				errorMsg: '',
				count: 1,
				isCollected: false // 收藏状态
			}
		},
		onLoad(options) {
			this.goodsId = options.goodsId ? Number(options.goodsId) : 0
			if (this.goodsId <= 0) {
				this.errorMsg = '商品ID无效'
				return
			}
			this.getGoodsDetail()
			this.checkCollectionStatus() // 初始化时检查收藏状态
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 处理分享
			handleShare() {
				uni.showActionSheet({
					itemList: ['分享给好友', '分享到朋友圈'],
					success: (res) => {
						if (res.tapIndex === 0) {
							uni.share({
								provider: 'weixin',
								type: 0,
								title: this.goodsInfo.goodsName,
								imageUrl: this.handleImgURL(this.goodsInfo.goodsImg),
								path: `/pages/goods/goodsDetail?goodsId=${this.goodsId}`,
								success: () => uni.showToast({
									title: '分享成功'
								})
							})
						}
					}
				})
			},

			// 处理图片URL
			handleImgURL(url) {
				if (!url || typeof url !== 'string') return '/static/images/default-goods.png'
				return url.startsWith('http') ? url : `${baseUrl}${url}`
			},

			// 获取商品详情
			async getGoodsDetail() {
				if (this.goodsId <= 0) {
					this.errorMsg = '商品ID无效';
					return;
				}
				this.loading = true;
				this.errorMsg = '';
				try {
					const res = await getDetailById(this.goodsId);

					// 增强错误检查
					if (!res) {
						throw new Error('获取商品详情失败：服务器未返回数据');
					}

					if ([200, 0].includes(res.code) && res.data) {
						this.goodsInfo = {
							...res.data,
							goodsPrice: Number(res.data.goodsPrice) || 0,
							originalPrice: Number(res.data.originalPrice) || 0,
							salesNum: Number(res.data.salesNum) || 0,
							isOnSale: res.data.isOnSale ?? 0,
							goodsDesc: res.data.goodsDesc || '暂无详细描述'
						};
					} else {
						throw new Error(res?.msg || `获取商品详情失败，错误码: ${res?.code}`);
					}
				} catch (err) {
					this.errorMsg = err.message;
					uni.showToast({
						title: err.message,
						icon: 'none',
						duration: 2000
					});
				} finally {
					this.loading = false;
				}
			},

			// 检查商品是否已收藏
			checkCollectionStatus() {
				try {
					const collectedGoods = uni.getStorageSync('collectedGoods') || []
					// 判断当前商品是否在收藏列表中
					this.isCollected = Array.isArray(collectedGoods) ?
						collectedGoods.some(item => item.goodsId === this.goodsId) :
						false
				} catch (e) {
					console.error('检查收藏状态失败：', e)
					this.isCollected = false
				}
			},

			// 切换收藏状态（添加/取消收藏）
			toggleCollect() {
				if (!this.goodsInfo.goodsName) return // 商品信息未加载完成时不操作

				try {
					// 从本地存储获取收藏列表
					let collectedGoods = uni.getStorageSync('collectedGoods') || []
					if (!Array.isArray(collectedGoods)) collectedGoods = []

					if (this.isCollected) {
						// 取消收藏：过滤掉当前商品
						collectedGoods = collectedGoods.filter(item => item.goodsId !== this.goodsId)
						uni.showToast({
							title: '已取消收藏'
						})
					} else {
						// 添加收藏：检查是否已存在，避免重复添加
						const isExisted = collectedGoods.some(item => item.goodsId === this.goodsId)
						if (!isExisted) {
							collectedGoods.push({
								goodsId: this.goodsId,
								goodsName: this.goodsInfo.goodsName,
								goodsImg: this.handleImgURL(this.goodsInfo.goodsImg),
								goodsPrice: this.goodsInfo.goodsPrice,
								collectTime: Date.now() // 记录收藏时间（用于排序）
							})
							uni.showToast({
								title: '收藏成功'
							})
						}
					}

					// 保存更新后的收藏列表到本地存储
					uni.setStorageSync('collectedGoods', collectedGoods)
					// 更新本地状态
					this.isCollected = !this.isCollected
				} catch (e) {
					console.error('操作收藏失败：', e)
					uni.showToast({
						title: '操作失败，请稍后重试',
						icon: 'none'
					})
				}
			},

			// 减少购买数量
			decreaseCount() {
				if (this.count > 1) this.count--
			},

			// 增加购买数量
			increaseCount() {
				this.count++
			},

			// 加入购物车（调用后端API）
			async addToCart() {
				if (this.count <= 0) {
					uni.showToast({
						title: '请选择购买数量',
						icon: 'none'
					})
					return
				}

				try {
					const res = await addCart({
						goodsId: this.goodsId,
						count: this.count
					})

					if ([200, 0].includes(res.code)) {
						uni.showToast({
							title: '已加入购物车',
							icon: 'success'
						})
						uni.$emit('cartCountChange')
						// 重置数量
						this.count = 1
					} else {
						throw new Error(res.msg || '加入购物车失败')
					}
				} catch (e) {
					console.error('加入购物车失败：', e)
					uni.showToast({
						title: e.message || '加入购物车失败，请稍后重试',
						icon: 'none'
					})
				}
			},

			// 立即购买
			buyNow() {
				if (this.count <= 0) {
					uni.showToast({
						title: '请选择购买数量',
						icon: 'none'
					})
					return
				}
				uni.navigateTo({
					url: `/pages/order/confirmOrder?goodsId=${this.goodsId}&count=${this.count}&goodsName=${encodeURIComponent(this.goodsInfo.goodsName)}&goodsImg=${encodeURIComponent(this.handleImgURL(this.goodsInfo.goodsImg))}&goodsPrice=${this.goodsInfo.goodsPrice}&storeId=${this.goodsInfo.storeId || 0}&storeName=${encodeURIComponent(this.goodsInfo.storeName || '未知店铺')}`
				})
			}
		}
	}
</script>

<style scoped>
	/* 页面基础样式 */
	.goods-detail-page {
		min-height: 100vh;
		background-color: #fff8f5;
		padding-bottom: 70px;
	}

	/* 导航栏样式 */
	.navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 16px 16px 12px;
		background-color: #fff;
		border-bottom: 1px solid #fee9e1;
		position: relative;
		z-index: 10;
	}

	.navbar-back {
		font-size: 20px;
		color: #2d3748;
	}

	.navbar-title {
		font-size: 18px;
		font-weight: 600;
		color: #2d3748;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 60%;
	}

	.navbar-right {
		display: flex;
		gap: 20px;
		font-size: 20px;
		color: #2d3748;
	}

	.navbar-icon {
		cursor: pointer;
	}

	.icon-collected {
		color: #e53e3e;
		/* 已收藏状态颜色 */
	}

	/* 商品图片样式 */
	.goods-img-container {
		background-color: #fff;
		padding: 10px;
	}

	.goods-img {
		width: 100%;
		border-radius: 8px;
		background-color: #faf0f5;
	}

	/* 商品基础信息样式 */
	.goods-base-info {
		background-color: #fff;
		padding: 16px;
		border-bottom: 1px solid #fee9e1;
	}

	.goods-name {
		font-size: 18px;
		color: #2d3748;
		line-height: 1.4;
		margin-top: 12px;
		display: block;
		word-break: break-all;
	}

	.goods-price-wrap {
		display: flex;
		align-items: baseline;
		gap: 12px;
		flex-wrap: wrap;
	}

	.goods-price {
		font-size: 20px;
		font-weight: 700;
		color: #e53e3e;
	}

	.goods-original-price {
		font-size: 14px;
		color: #718096;
		text-decoration: line-through;
	}

	.goods-sales {
		font-size: 14px;
		color: #718096;
	}

	/* 商品描述样式 */
	.goods-desc-container {
		background-color: #fff;
		padding: 16px;
		margin-top: 8px;
	}

	.desc-title {
		font-size: 16px;
		font-weight: 600;
		color: #2d3748;
		margin-bottom: 8px;
		display: block;
	}

	.goods-desc {
		font-size: 14px;
		color: #4a5568;
		line-height: 1.6;
	}

	/* 加载中样式 */
	.loading-container {
		padding: 40px 0;
		text-align: center;
	}

	.loading-spinner {
		width: 30px;
		height: 30px;
		border: 4px solid #fee9e1;
		border-top-color: #e53e3e;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin: 0 auto;
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	/* 错误提示样式 */
	.error-container {
		padding: 40px 20px;
		text-align: center;
	}

	.error-icon {
		font-size: 24px;
		color: #e53e3e;
		display: block;
		margin-bottom: 12px;
	}

	.error-text {
		font-size: 14px;
		color: #718096;
		margin-bottom: 20px;
		display: block;
	}

	.retry-btn {
		background-color: #e53e3e;
		color: #fff;
		border: none;
		padding: 8px 20px;
		border-radius: 20px;
		font-size: 14px;
	}

	/* 底部操作栏 - 美化核心部分 */
	.cart-operate-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		background-color: #fff;
		padding: 8px 16px;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		height: 70px;
	}

	/* 数量控制按钮 - 美化 */
	.count-control {
		display: flex;
		align-items: center;
		background-color: #fff8f5;
		border-radius: 25px;
		overflow: hidden;
		width: 120px;
		height: 45px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.count-btn {
		width: 40px;
		height: 100%;
		border: none;
		background-color: transparent;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20px;
		color: #2d3748;
		padding: 0;
	}
	/* 减号按钮 */
	.minus-btn {
		color: #718096;
	}
	.minus-btn:disabled {
		color: #e2e8f0;
	}
	/* 加号按钮 */
	.plus-btn {
		color: #e53e3e;
	}
	.count-icon {
		line-height: 1;
	}
	.count-num {
		font-size: 16px;
		color: #2d3748;
		font-weight: 500;
		width: 40px;
		text-align: center;
	}

	/* 操作按钮 - 美化 */
	.add-to-cart-btn, .buy-now-btn {
		flex: 1;
		height: 45px;
		border: none;
		border-radius: 25px;
		font-size: 16px;
		font-weight: 500;
		margin: 0 8px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.add-to-cart-btn {
		background-color: #fff8f5;
		color: #e53e3e;
		border: 1px solid #fee9e1;
	}
	.buy-now-btn {
		background: linear-gradient(135deg, #e53e3e, #c53030);
		color: #fff;
		box-shadow: 0 2px 6px rgba(229, 62, 62, 0.2);
	}
	.btn-text {
		line-height: 1;
	}

	/* 下架样式 */
	.offline {
		justify-content: center;
		color: #718096;
		font-size: 14px;
	}
</style>